package controllers;

import models.entities.ShoppingCartEntity;
import models.entities.ShoppingCartItem;
import models.exceptions.CreateEntityException;
import models.exceptions.DeleteEntityException;
import models.exceptions.GetEntityException;
import models.exceptions.UpdateEntityException;
import models.helpers.StringHelper;
import models.helpers.UserHelper;
import models.repository.ShoppingCartRepositorySQL;
import models.repository.common.ShoppingCartRepository;
import models.shop.User;
import play.mvc.Controller;

import java.io.IOException;
import java.util.List;

public class ShoppingCart extends Controller {
    @Deprecated
    private static ShoppingCartRepository repository = new ShoppingCartRepositorySQL();

    public static void add(int id) throws CreateEntityException, GetEntityException, IOException {
        models.shop.User user = UserHelper.getUser(session);
        repository.addProduct(id, user.id);
        display();
    }

    public static void display() throws CreateEntityException, GetEntityException, IOException {
        User user = UserHelper.getUser(session);
        ShoppingCartEntity shoppingCart = repository.getShoppingCart(user.id);
        if (shoppingCart.items.size() == 0) {
            render("ShoppingCart/empty.html");
            return;
        }
        render(shoppingCart);
    }

    public static void update(List<String> products) throws CreateEntityException, GetEntityException, UpdateEntityException, IOException {
        User user = UserHelper.getUser(session);
        ShoppingCartEntity shoppingCart = repository.getShoppingCart(user.id);
        for (int i = 0; i < shoppingCart.items.size(); i++) {
            ShoppingCartItem shoppingItem = shoppingCart.items.get(i);
            if (StringHelper.isNumeric(products.get(i))) {
                shoppingItem.quantity = Integer.parseInt(products.get(i));
            }
        }
        repository.update(shoppingCart, user.id);
        if (request.params.get("completeCheckout") != null){
            Order.summary();
        }
        else if (request.params.get("update") != null) {
            display();
        }
    }

    public static void delete(int productId) throws CreateEntityException, GetEntityException, DeleteEntityException, IOException {
        User user = UserHelper.getUser(session);
        repository.delete(productId, user.id);
        display();
    }
}
